<template>
  <div class="cart-page">
    <h1 class="page-title">购物车</h1>

    <!-- 购物车列表 -->
    <el-table
        :data="cartItems"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <!-- 多选框 -->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="菜品名称" align="center" prop="dishName" />
      <el-table-column label="菜品图片" align="center">
        <template #default="{ row }">
          <el-image
              style="width: 100px; height: 100px"
              :src="row.dishImage"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center">
        <template #default="{ row }">
          {{ row.dishPrice }}元
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center">
        <template #default="{ row }">
          <el-input-number
              v-model="row.quantity"
              :min="1"
              @change="updateCartItem(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center">
        <template #default="{ row }">
          {{ row.dishPrice * row.quantity }}元
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="danger" @click="deleteCartItem(row.cartId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="fetchCartItems"
        @size-change="handlePageSizeChange"
    />

    <!-- 结算区域 -->
    <div class="checkout-section">
      <p class="total-price">选中总价：{{ selectedTotalPrice }}元</p>
      <el-button
          type="primary"
          @click="checkout"
          :disabled="selectedItems.length === 0"
      >
        去结算
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { apiGet, apiPost } from '@/utils/api';
import type { CartItem } from '@/types/entity';
import {useRouter} from "vue-router";
import {sessionStorage} from "@/utils/storage";
const router = useRouter();
// 定义响应式的购物车列表
const cartItems = ref<CartItem[]>([]);

// 分页参数
const pageNo = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总条数

// 选中的菜品
const selectedItems = ref<CartItem[]>([]);

// 从后端获取购物车数据
const fetchCartItems = async () => {
  const { data } = await apiGet('/cart/findAll', {
    page: pageNo.value,
    limit: pageSize.value,
  });
  cartItems.value = data.data; // 假设返回的数据结构为 { data: CartItem[], total: number }
  total.value = data.count; // 更新总条数
};

// 更新购物车中菜品的数量
const updateCartItem = async (item: CartItem) => {
  await apiPost('/cart/edit', {
    cartId: item.cartId,
    quantity: item.quantity,
  });
};

// 删除购物车中的菜品
const deleteCartItem = async (cartId: number) => {
  await ElMessageBox.confirm('确定删除该菜品吗？', '提示', {
    type: 'warning',
  });
  await apiPost('/cart/delete', { cartId });
  await fetchCartItems();
};

// 处理选中项变化
const handleSelectionChange = (selection: CartItem[]) => {
  selectedItems.value = selection;
};

// 计算选中项的总价
const selectedTotalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + item.dishPrice * item.quantity;
  }, 0);
});

// 处理分页大小变化
const handlePageSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  pageNo.value = 1; // 重置页码
  fetchCartItems(); // 重新加载数据
};

// 结算功能
const checkout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择至少一个菜品');
    return;
  }

  // 将选中的菜品信息存储到 sessionStorage
  sessionStorage.set(
      'selectedDishes',
      JSON.stringify(
          selectedItems.value.map(item => ({
            dishId: item.dishId,
            name: item.dishName,
            price: item.dishPrice,
            quantity: item.quantity,
            imageUrl: item.dishImage,
          }))
      )
  );

  // 跳转到多选结算页面
  router.push('/checkout/multi');
};

// 在组件挂载时获取购物车数据
onMounted(() => {
  fetchCartItems();
});
</script>

<style scoped>
.cart-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.checkout-section {
  margin-top: 20px;
  text-align: right;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>